﻿namespace WebDevUtilities.CssSpriteGenerator
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Windows;
    using System.Windows.Controls;
    using EnvDTE;
    using EnvDTE80;
    using Microsoft.VisualStudio.Shell;
    using Logic;
    using Resources;

    public partial class CssSpriteGeneratorToolWindowControl : UserControl
    {
        private OutputWindowPane outputWP;
        private DTE2 dte = Package.GetGlobalService(typeof(DTE)) as DTE2;
        private LayoutProperties layoutProp = new LayoutProperties();
        public bool done = false;
        Project _project;

        private OutputWindowPane InitializeOutputWindow()
        {
            EnvDTE.Window win = dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput);
            OutputWindow outputWindow = (OutputWindow)win.Object;
            OutputWindowPane outputWindowPane = outputWindow.OutputWindowPanes.Add(Common.ToolWindowTitle);
            return outputWindowPane;
        }

        public CssSpriteGeneratorToolWindowControl()
        {
            outputWP = InitializeOutputWindow();
            InitializeComponent();
            foreach (ImageFileExtension imgFileExtension in Enum.GetValues(typeof (ImageFileExtension)))
            {
                ComboBoxItem cboxitem = new ComboBoxItem {Content = imgFileExtension.ToString()};
                CbOutputImageExt.Items.Add(cboxitem);
            }
            foreach (StylsheetFileExtension imgFileExtension in Enum.GetValues(typeof (StylsheetFileExtension)))
            {
                ComboBoxItem cboxitem = new ComboBoxItem {Content = imgFileExtension.ToString()};
                CbOutputCssExt.Items.Add(cboxitem);
            }
        }

        private void BtnGenerateClick(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(TbOutputImageName.Text) && !string.IsNullOrWhiteSpace(TbOutputCssName.Text))
            {
                if (CheckValidFileExt())
                {
                    try
                    {
                        IsEnabled = false;
                        _project = null;
                        layoutProp.InputFilePaths = GetInputFilePaths();
                        if (layoutProp.InputFilePaths.Length != 0)
                        {
                            FileInfo fileInfo = new FileInfo(layoutProp.InputFilePaths[0]);
                            layoutProp.OutputSpriteFilePath = fileInfo.DirectoryName + @"\" + TbOutputImageName.Text + "." + CbOutputImageExt.Text.ToLower();
                            layoutProp.OutputCssFilePath = fileInfo.DirectoryName + @"\" + TbOutputCssName.Text + "." + CbOutputCssExt.Text.ToLower();
                            layoutProp.DistanceBetweenImages = NumDistanceBetweenImages.NumValue;
                            layoutProp.MarginWidth = NumMarginWidth.NumValue;
                            layoutProp.ImagesInColumn = NumImagesInCol.NumValue;
                            layoutProp.ImagesInRow = NumImagesInRow.NumValue;
                            layoutProp.SpriteClassname = TbSpriteClassname.Text;
                            if (RbUseCustomClassname != null && RbUseCustomClassname.IsChecked != null)
                            { layoutProp.UseCustomClassname = RbUseCustomClassname.IsChecked.Value; }
                            layoutProp.CustomClassname = TbCustomClassname.Text;
                            if (RbAutomatic != null && RbAutomatic.IsChecked != null && RbAutomatic.IsChecked.Value)
                            { layoutProp.Layout = "Automatic"; }
                            else if (RbHorizontal != null && RbHorizontal.IsChecked != null && RbHorizontal.IsChecked.Value)
                            { layoutProp.Layout = "Horizontal"; }
                            else if (RbVertical != null && RbVertical.IsChecked != null && RbVertical.IsChecked.Value)
                            { layoutProp.Layout = "Vertical"; }
                            else if (RbRectangular != null && RbRectangular.IsChecked != null && RbRectangular.IsChecked.Value)
                            { layoutProp.Layout = "Rectangular"; }
                            Sprite sprite = new Sprite(layoutProp);
                            sprite.Create();
                            _project.ProjectItems.AddFromFile(layoutProp.OutputCssFilePath);
                            AddConsoleEntry("file '" + layoutProp.OutputCssFilePath + "' added to project");
                            _project.ProjectItems.AddFromFile(layoutProp.OutputSpriteFilePath);
                            AddConsoleEntry("file '" + layoutProp.OutputSpriteFilePath + "' added to project");
                            AddConsoleEntry("All done!");
                        }
                        else
                        {
                            MessageBox.Show("No files selected!", "Check selection!", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        IsEnabled = true;
                    }
                    catch (Exception ex)
                    {
                        AddConsoleEntry("Unknown Error: '" + ex.Message + "'");
                        MessageBox.Show("Check Output Window", "Unknown Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        IsEnabled = true;
                    }
                }
                else
                {
                    MessageBox.Show("No valid files selected!", "Check selection!", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            else
            {
                MessageBox.Show("Please fill all textboxes!", "Empty Fields!", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private bool CheckValidFileExt()
        {
            if (dte != null)
            {
                UIHierarchy solutionExplorer = dte.ToolWindows.SolutionExplorer;
                var items = solutionExplorer.SelectedItems as Array;
                if (items != null && items.Length != 0)
                {
                    foreach (UIHierarchyItem hierarchyItem in items)
                    {
                        ProjectItem prjItem = hierarchyItem.Object as ProjectItem;
                        if (prjItem != null)
                        {
                            string prjItemPath = prjItem.Properties.Item(Logic.Constants.ProjectItemPropertyFullPath).Value.ToString();
                            FileInfo fileInfo = new FileInfo(prjItemPath);
                            string fileTypeExt = fileInfo.Extension.ToLower();
                            switch (fileTypeExt)
                            {
                                case FileType.PNG:
                                case FileType.JPG:
                                case FileType.JPEG:
                                case FileType.GIF:
                                case FileType.BMP:
                                    return true;
                            }
                        }
                    }
                }
            }
            return false;
        }

        private string[] GetInputFilePaths()
        {
            List<string> filePaths = new List<string>();
            if (dte != null)
            {
                UIHierarchy solutionExplorer = dte.ToolWindows.SolutionExplorer;
                var items = solutionExplorer.SelectedItems as Array;
                if (items != null || items.Length == 0)
                {
                    foreach (UIHierarchyItem hierarchyItem in items)
                    {
                        ProjectItem prjItem = hierarchyItem.Object as ProjectItem;
                        string prjItemPath = prjItem.Properties.Item(Logic.Constants.ProjectItemPropertyFullPath).Value.ToString();
                        FileInfo fileInfo = new FileInfo(prjItemPath);
                        string fileTypeExt = fileInfo.Extension.ToLower();
                        switch (fileTypeExt)
                        {
                            case FileType.PNG:
                            case FileType.JPG:
                            case FileType.JPEG:
                            case FileType.GIF:
                            case FileType.BMP:
                                filePaths.Add(prjItemPath);
                                AddConsoleEntry("file '" + prjItemPath + "' added to sprite");
                                break;
                        }
                        if (_project == null)
                        {
                            _project = prjItem.ContainingProject;
                        }
                    }
                }
            }
            return filePaths.ToArray();
        }

        public void AddConsoleEntry(string entry)
        {
            outputWP.OutputString(DateTime.Now + ": " + entry + Environment.NewLine);
        }

        private void RbRectangularUnchecked(object sender, RoutedEventArgs e)
        {
            if (RbRectangular != null && RbRectangular.IsChecked != null) 
                StkPnlLayoutRectangular.IsEnabled = RbRectangular.IsChecked.Value;
        }

        private void RbRectangularChecked(object sender, RoutedEventArgs e)
        {
            if (RbRectangular != null && RbRectangular.IsChecked != null) 
                StkPnlLayoutRectangular.IsEnabled = RbRectangular.IsChecked.Value;
        }

        private void RbUseCustomClassnameChecked(object sender, RoutedEventArgs e)
        {
            if (RbUseCustomClassname != null && RbUseCustomClassname.IsChecked != null) 
                TbCustomClassname.IsEnabled = RbUseCustomClassname.IsChecked.Value;
        }

        private void RbUseImagefilenameChecked(object sender, RoutedEventArgs e)
        {
            if (RbUseCustomClassname != null && RbUseCustomClassname.IsChecked != null) 
                TbCustomClassname.IsEnabled = RbUseCustomClassname.IsChecked.Value;
        }

        private void ChkBoxUseCustomCssPathChecked(object sender, RoutedEventArgs e)
        {
            if (ChkBoxUseCustomCssPath != null && ChkBoxUseCustomCssPath.IsChecked != null)
                TbCustomCssPath.IsEnabled = ChkBoxUseCustomCssPath.IsChecked.Value;
        }

        private void ChkBoxUseCustomImgPath_Checked(object sender, RoutedEventArgs e)
        {
            if (ChkBoxUseCustomImgPath != null && ChkBoxUseCustomImgPath.IsChecked != null)
                TbCustomImgPath.IsEnabled = ChkBoxUseCustomImgPath.IsChecked.Value;
        }
    }
}